package com.pineapple.module.core.harvest.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.pineapple.module.core.harvest.domain.Harvest;
import com.pineapple.module.core.harvest.domain.HarvestCriteria;

public class HarvestDAO {

	protected int count(HarvestCriteria criteria,Connection conn) throws Exception{
 		int totRecord =0;

		StringBuilder sql = new StringBuilder();
		sql.append("SELECT COUNT(*) AS TOT  ");
		sql.append("FROM ");
		sql.append("harvest as h ");
		sql.append("Inner Join planting ON h.harvest_area = planting.planting_id ");
		sql.append("Inner Join area ON planting.area_id = area.area_id ");
		sql.append("WHERE 1=1 ");

		if(criteria.getharvestId()!=null && !criteria.getharvestId().equals("")){
			sql.append("AND h.harvest_Id='"+criteria.getharvestId()+"' ");
		}
		if(criteria.getharvestArea()!=null && !criteria.getharvestArea().equals("")){
			sql.append("AND h.harvest_area='"+criteria.getharvestArea()+"' ");
		}
		if(criteria.getharvestDateFrom()!=null && !criteria.getharvestDateFrom().equals("")){
			sql.append("AND h.harvest_date  >='"+dateForInsert(criteria.getharvestDateFrom())+"' ");
		}
		if(criteria.getharvestDateTo()!=null && !criteria.getharvestDateTo().equals("")){
			sql.append("AND h.harvest_date <='"+dateForInsert(criteria.getharvestDateTo())+"' ");
		}

		try(Statement stmt = conn.createStatement()){
			ResultSet rst = stmt.executeQuery(sql.toString());
			if (rst.next()) {
				totRecord = rst.getInt("TOT");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}
		return totRecord;
	}


	protected List<Harvest> search(HarvestCriteria criteria,Connection conn) throws Exception{
		List<Harvest> lstHarvest = new ArrayList<Harvest>();
		Harvest harvest = null;
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ");
		sql.append("h.harvest_Id,");
		sql.append("h.harvest_date,");
		sql.append("h.harvest_area,");
		sql.append("h.harvest_value,");
		sql.append("planting.planting_status, ");
		sql.append("planting.area_id, ");
		sql.append("planting.planting_id, ");
		sql.append("a.area_name ");
		sql.append("FROM ");
		sql.append("harvest as h ");
		sql.append("Inner Join planting ON h.harvest_area = planting.planting_id ");
		sql.append("Inner Join area a ON planting.area_id = a.area_id ");
		sql.append("WHERE 1=1 ");

		if(criteria.getharvestId()!=null && !criteria.getharvestId().equals("")){
			sql.append("AND h.harvest_Id='"+criteria.getharvestId()+"' ");
		}
		if(criteria.getharvestArea()!=null && !criteria.getharvestArea().equals("")){
			sql.append("AND h.harvest_area='"+criteria.getharvestArea()+"' ");
		}
		if(criteria.getharvestDateFrom()!=null && !criteria.getharvestDateFrom().equals("")){
			sql.append("AND h.harvest_date  >='"+dateForInsert(criteria.getharvestDateFrom())+"' ");
		}
		if(criteria.getharvestDateTo()!=null && !criteria.getharvestDateTo().equals("")){
			sql.append("AND h.harvest_date <='"+dateForInsert(criteria.getharvestDateTo())+"' ");
		}

		System.out.println(sql.toString());

		try(Statement stmt = conn.createStatement()){
			  ResultSet rs = stmt.executeQuery(sql.toString());
		        while(rs.next()) {
		        	harvest= new Harvest();
		        	harvest.setHarvestArea(rs.getString("area_name"));
		        	harvest.setHarvestId(rs.getString("harvest_Id"));
		        	harvest.setHarvestAreaId(rs.getString("planting_id"));
		        	harvest.setHarvestValue(rs.getString("harvest_value"));
		        	harvest.setHarvestDate(dateForShow(rs.getDate("harvest_date")));
		        	harvest.setPlantingStatus(rs.getString("planting_status"));
		        	lstHarvest.add(harvest);
		        }
		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}
		return lstHarvest;
	}

	protected Map<String,String> areaCombo(Connection conn)throws Exception{
		Map<String,String> lstArea = new HashMap<String, String>();
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT * FROM area	 ");
		try(Statement stmt = conn.createStatement()){
			ResultSet rs = stmt.executeQuery(sql.toString());
			while(rs.next()) {
				lstArea.put(rs.getString("Area_id"),rs.getString("Area_name"));
			}
		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}
		return lstArea;
	}

	protected void add(Connection conn, Harvest harvest)throws Exception{
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO harvest (harvest_date" +
				",harvest_area,harvest_value ) ");
		sql.append("VALUES ( " );
		sql.append("'"+dateForInsert(harvest.getHarvestDate())+"' ");
		sql.append(",'"+harvest.getHarvestAreaId()+"' ");
		sql.append(",'"+harvest.getHarvestValue()+"' ");
		sql.append(" )");
		System.out.println(sql.toString());
		try(Statement stmt = conn.createStatement()){
			 stmt.executeUpdate(sql.toString());
		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}
	}


	protected void edit(Connection conn, Harvest harvest)throws Exception{

		StringBuilder sql = new StringBuilder();
		sql.append("UPDATE Harvest SET ");
		sql.append(" harvest_date='"+dateForInsert(harvest.getHarvestDate())+"' ");
		sql.append(",harvest_area='"+harvest.getHarvestArea()+"' ");
		sql.append(",harvest_value='"+harvest.getHarvestValue()+"' ");
		sql.append(" WHERE harvest_id="+harvest.getHarvestId());

		System.out.println(sql.toString());
		try(Statement stmt = conn.createStatement()){
			stmt.executeUpdate(sql.toString());

		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}
	}

	protected void delete(Connection conn, String harvestIds)throws Exception{

		StringBuilder sql = new StringBuilder();
		sql.append("DELETE FROM harvest  ");
		sql.append(" WHERE harvest_id IN ("+harvestIds+")");
		System.out.println(sql.toString());
		try(Statement stmt = conn.createStatement()){
			stmt.executeUpdate(sql.toString());
		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}
	}


	protected Harvest searchById(Connection conn,int id)throws Exception{

		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ");
		sql.append("harvest.harvest_Id, ");
		sql.append("harvest.harvest_date, ");
		sql.append("harvest.harvest_area, ");
		sql.append("harvest.harvest_value, ");
		sql.append("planting.planting_status ");
		sql.append("FROM ");
		sql.append("harvest ");
		sql.append("Inner Join planting ON planting.planting_id = harvest.harvest_area ");
		sql.append("WHERE harvest_Id ="+id);
		Harvest harvest = null;
		System.out.println(sql);
		try(Statement stmt = conn.createStatement()){
			  ResultSet rs = stmt.executeQuery(sql.toString());
			  harvest  = new Harvest();
		        if(rs.next()) {
		        	harvest.setHarvestId(rs.getString("harvest_id"));
		        	harvest.setHarvestArea(rs.getString("harvest_area")+","+rs.getString("planting_status"));
		        	harvest.setHarvestDate(dateForShow(rs.getDate("harvest_date")));
		        	harvest.setHarvestValue(rs.getString("harvest_value"));
		        	harvest.setPlantingStatus(rs.getString("planting_status"));
		        }
		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}
		return harvest;
	}

	protected Map<String,String> searchComboPlantAndArea(Connection conn) throws Exception{
		StringBuilder sql = new StringBuilder();
		Map<String,String> lstArea = new LinkedHashMap<String, String>();
		sql.append("SELECT a.area_name,p.planting_id,a.area_id,p.planting_status ");
		sql.append("FROM planting p INNER JOIN area a ON p.area_id = a.area_id ");
		sql.append("WHERE p.planting_status=3 or p.planting_status=6");
		try(Statement stmt = conn.createStatement()){
			ResultSet rs = stmt.executeQuery(sql.toString());
	        while(rs.next()) {
	        	lstArea.put(rs.getString("planting_id")+","+rs.getString("planting_status"), rs.getString("area_name"));
	        }
		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}
		return lstArea;
	}


	protected void updateStatus(Connection conn,String plantingId,int status)throws Exception{
		StringBuilder sql = new StringBuilder();
		sql.append("UPDATE  planting SET ");
		sql.append("planting_status='"+status+"' ");
		sql.append(" WHERE planting_id='"+plantingId+"' ");
		System.out.println(sql.toString());
		try(Statement stmt = conn.createStatement()){
			stmt.executeUpdate(sql.toString());
		}catch(Exception ex){
			ex.printStackTrace();
			throw ex;
		}

	}
	public static String dateForShow(Date date){
		String returnValue = null;
		try {
			if(date != null){
				returnValue = convertToString(date,"dd/MM/yyyy");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnValue;
	}

	public static String convertToString(Date date, String format) {
		if (date != null) {
			SimpleDateFormat formatDate = new SimpleDateFormat(format.toString(),Locale.ENGLISH);
			StringBuilder fdate = new StringBuilder(formatDate.format(date));
			return fdate.toString();
		} else {
			return "";
		}
	}


	public static String dateForInsert(String date){
		String returnValue = null;
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", new Locale("en", "EN"));
		try {
			if(date != null && !date.trim().equals("")){
				returnValue = convertToString(sdf.parse(date),"yyyy-MM-dd");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnValue;
	}

	   protected int countStatus(Connection conn , String areaId) throws Exception{
			StringBuilder sql = new StringBuilder();
			int i = 0;
			sql.append("SELECT COUNT(*) AS tot FROM planting  ");
			sql.append("WHERE planting.planting_status = '4' or planting.planting_status = '7' ");
			sql.append("And area_id = '"+areaId+"' ");
			try(Statement stmt = conn.createStatement()){
				ResultSet rs = stmt.executeQuery(sql.toString());
				if(rs.next()) {
				   i = rs.getInt("tot");
				}
			}catch(Exception ex){
				ex.printStackTrace();
				throw ex;
			}
			return i;
	    }
}
